<template>
	<view class="content">
		<view class="section-0">
			<view class="top">
				<view class="user-info">
					<view class="logo">
						<image mode="aspectFill" src="../../../../../src/imgs/test.jpg"></image>
					</view>
					<view class="info">
						<view class="name">
							<view class="icon">
								<image mode="aspectFit" src="../../../../../src/imgs/account-icon-user.png"></image>
							</view>
							<text>{{userInfo.nick_name}}</text>
						</view>
						<view class="job">
							<view class="icon">
								<image mode="aspectFit" src="../../../../../src/imgs/account-icon-card.png"></image>
							</view>
							<text>{{curRole}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="section-1">
			<view class="section-body">
				<text class="iconfont icon-xiangmu"></text>项目：{{curProject.project_name}}
			</view>
		</view>
		<view class="section-2">
			<view class="section-body">
				<view class="title">
					履职
					<!-- <view v-if="curRole === '项目经理'" class="delegate">委派</view> -->
				</view>
				<view  :class="`duty-action ${scene ? '' : 'duty-action__disabled'}`" @click="submit()">
					<view class="sub-title">
						<!-- {{scene ? '现场履职' : '不在考勤范围内'}}{{form.type}} -->
						{{title}}
					</view>
					<view class="duty-time">{{curTime}}</view>
				</view>
				<view class="location">
					<text class="iconfont icon-addresss"></text>{{curLocation.address}}
				</view>
				<!-- <view class="warning" v-if="!scene">（当前位置不在施工现场，仅能不在考勤范围内）</view> -->
			</view>
		</view>
		<view class="section-3">
			<view class="section-body">
				<view class="title">考勤记录</view>
				<view class="list">
					<div class="item-wrapper">
						<view class="item" v-for="item in list" :key="item.id">
							<view class="record" v-if="item.dk_time_out">{{item.user_name}}：{{item.dk_time_out}} (出场)</view>
							<view class="record">{{item.user_name}}：{{item.dk_time_in}} (进场)</view>
						</view>
					</div>
				</view>
			</view>
		</view>
		<u-popup mode="center" :show="showQuestion" @close="closeQuestionPop" :round="50">
			<view class="pop project-pop">
				<view class="title">
					<text>工作描述</text>
				</view>
				<view class="body">
					<view class="wrapper _scroll">
						<view class="section-4">
							<view class="form-item upload-wrap">
								<view class="label">相关照片</view>
								<u-upload :fileList="fileList" :previewFullImage="true" @afterRead="afterRead"
									@delete="deletePic" multiple :maxCount="1"
									:style="{position:'relative',height:fileList.length == 0 ? '44rpx' : 'unset',border: fileList.length == 0 ? 'solid 2rpx #1534ce' : 'none', borderRadius: '20rpx'}">
									<view class="iconfont icon-tupian"></view>
								</u-upload>
							</view>
							<view class="form-item textarea-wrap">
								<view class="label">问题描述</view>
								<view class="text-area">
									<u--textarea
										:maxlength="-1"
										placeholderClass="input-placeholder"
										class="text-body"
									    placeholder="输入备注内容..."
									    v-model="form.remark"
										border='null'
									  ></u--textarea>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="actions">
					<view class="custom-button cancel" @click="closeQuestionPop()">
						取消
					</view>
					<view class="custom-button" @click="submit">
						提交
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		addProject,
	} from '@/api/patrol.js';
	import { projectSignInAddApi, projectSignInIndexApi, projectSignInSignApi } from '@/api/duty.js';
	import { mapGetters, mapActions} from 'vuex';
	import { uploadUrl } from '@/baseUrl.js';
	export default {
		data() {
			return {
				showQuestion: false,
				fileList: [],
				list: [],
				title:'不在考勤范围内',
				form: {
					project_id: '',
					user_id: '',
					dk_address: '',
					mark: '', // 是否现场履职原因
					type: '进场', // 进出
					remark: '', // 不在考勤范围内原因
					photo_id: '',
				},
				curTime: '',
				timer: null,
				scene: false,
			};
		},
		computed: {
			...mapGetters({
				curRole: 'system/getCurRole', 
				userInfo: 'system/getUserInfo', 
				curProject: 'system/getCurProject', 
				curLocation: 'system/getCurLocation'
			}),
		},
		onReady() {
			this.formatDate();
			this.timer = setInterval(() => {
				this.formatDate();
			}, 1000);
			this.projectSignInSign();
			// this.getDistance(this.curLocation.latitude, this.curLocation.longitude, this.curProject.latitude, this.curProject.longitude);
			this.fetchList();
		},
		beforeDestroy() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		},
		methods: {
			async projectSignInSign() {
				uni.showLoading({title: '加载中...'});
				const { data } = await projectSignInSignApi({
					project_id: this.curProject.id,
					latitude: this.curLocation.latitude || '120.067600',
					longitude: this.curLocation.longitude || '31.943697',
				});
				uni.hideLoading();
				if (data.code === 1) {
					if (data.data == 1) {
						this.scene = true;
						this.title = '已进入考勤范围';
					} else {
						this.scene = false;
						this.title = '不在考勤范围内';
					}
				}
			},
			getDistance(lat1, lng1, lat2, lng2) {
				if (!lat1 || !lng1 || !lat2 || !lng2) {
					return 999;
				}
				var radLat1 = lat1*Math.PI / 180.0;
				var radLat2 = lat2*Math.PI / 180.0;
				var a = radLat1 - radLat2;
				var b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
				Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
				s = s *6378.137 ;
				s = Math.round(s * 10000) / 10000;
				if (s <= 2) {
					this.scene = true;
				} else {
					this.scene = false;
				}
			},
			formatDate() {
				const date =new Date();//时间戳为10位需*1000，时间戳为13位的话不需乘1000
			    const h = (date.getHours() < 10 ? "0" + date.getHours() :  date.getHours()) + ':';
			    const m = (date.getMinutes() < 10 ? "0" + date.getMinutes() :  date.getMinutes()) + ':';
			    const s = (date.getSeconds() < 10 ? "0" + date.getSeconds() :  date.getSeconds());
			   	this.curTime =  h + m + s;  
			},
			formatDateAll() {
				const date =new Date();//时间戳为10位需*1000，时间戳为13位的话不需乘1000
				const Y = date.getFullYear() +'-';
				const M = (date.getMonth() +1 <10 ?'0' + (date.getMonth() +1) : date.getMonth() +1) +'-';
				const D = date.getDate();
				
			    const h = (date.getHours() < 10 ? "0" + date.getHours() :  date.getHours()) + ':';
			    const m = (date.getMinutes() < 10 ? "0" + date.getMinutes() :  date.getMinutes()) + ':';
			    const s = (date.getSeconds() < 10 ? "0" + date.getSeconds() :  date.getSeconds());
			   	return Y + M + D + ' ' + h + m + s;  
			},
			closeQuestionPop() {
				this.showQuestion = false
			},
			// 删除图片
			deletePic(event) {
				this[`fileList`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList`].length
				console.log(this[`fileList`])
				lists.map((item) => {
					this[`fileList`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList`][fileListLen]
					this[`fileList`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.data.file_id
					}))
					fileListLen++
				}
			},
			isToday(date) {
			  return new Date(date).toDateString()==new Date().toDateString();
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: uploadUrl, // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								resolve(JSON.parse(res.data))
							}, 1000)
						}
					});
				})
			},
			async fetchList() {
				uni.showLoading({title: '加载中...'});
				const { data } = await projectSignInIndexApi({
					project_id: this.curProject.id,
					user_name: this.userInfo.nick_name
				});
				uni.hideLoading();
				if (data.code === 1) {
					this.list = data.data.data;
					if (this.list.length && this.list[0].type === '进场') {
						this.form.type = '出场'
					} else {
						this.form.type = '进场'
					}
				}
			},
			submit() {
				// this.form.project_id = this.curProject.id;
				// this.form.user_id = this.userInfo.user_id;
				// this.form.photo_id = this[`fileList`].length > 0 ? this[`fileList`][0].url : '';
				// this.form.dk_address = this.curLocation.address;
				// this.form.mark = this.scene ? '现场履职' : '不在考勤范围内';
				if (!this.scene) {
					uni.showToast({
						title: '不在考勤范围内',
						icon: 'error',
						duration: 1000
					})
					return;
				}
				let obj = {
					project_id: this.curProject.id,
					user_id: this.userInfo.user_id,
					dk_address: this.curLocation.address,
					id: '',
					dk_time_in: '',
					dk_time_out: '',
					mark: this.scene ? '现场履职' : '不在考勤范围内'
				}
				let latest = this.list[0];
				if (latest && this.isToday(latest.dk_time_in) && !latest.dk_time_out) {
					obj.id = latest.id;
					obj.dk_time_out = this.formatDateAll();
					delete obj.dk_time_in;
				} else {
					obj.dk_time_in = this.formatDateAll();
				}
				for (let key in obj) {
					if (obj[key] == '') {
						delete obj[key]
					}
				}
				uni.showLoading({title: '加载中...'});
				projectSignInAddApi({
					...obj
				}).then(res => {
					if (res.data.code == 1 || res.data.code == 200) {
						uni.showToast(
							{title: '打卡成功',  duration: 1000, icon: 'success' }
						);
						for (let key in this.form) {
							this.form[key] = ''
						}
						this.showQuestion = false
					} else {
						uni.showToast(
							{title: '打卡失败',  duration: 1000, icon: 'error' }
						);
					}
					uni.hideLoading();
					this.fetchList();
				}).catch(() => {
					uni.hideLoading();
				})
			},
		},
		onNavigationBarButtonTap(res) {
			// if(this.curRole === '项目经理') {
			// 	uni.navigateTo({
			// 		url: '/pages/work/manager/work_manage/duty/summary/index'
			// 	})
			// } else {
			// 	uni.navigateTo({
			// 		url: '/pages/work/center/duty/summary/index'
			// 	})
			// }
			uni.navigateTo({
				url: '/pages/work/center/duty/summary/index'
			})
			
		}
	}
</script>

<style lang="scss" scoped>
	.section-3{
		width: 100%;
		background-color: #fff;
		.section-body{
			box-shadow: 0 -28rpx 28rpx 14rpx rgba(#bcbcb5, 0.17);
			background-color: #fff;
			padding-top: 40rpx;
			border-top-left-radius: 50rpx;
			border-top-right-radius: 50rpx;
			overflow: hidden;
			box-sizing: border-box;
			.list{
				padding-top: 15rpx;
				.item{
					width: 100%;
					.record{
						width: 100%;
						height: 54rpx;
						border-bottom: 1rpx solid rgba(0, 0, 0, 0.2);
						box-sizing: border-box;
						padding: 0 60rpx;
						text-overflow: ellipsis;
						white-space: nowrap;
						overflow: hidden;
						height: 54rpx;
						line-height: 54rpx;
						font-size: 26rpx;
						font-weight: 300;
						font-stretch: normal;
						letter-spacing: 0rpx;
						color: #000000;
					}
				}
			}
			.title{
				font-size: 26rpx;
				font-weight: bold;
				font-stretch: normal;
				line-height: 34rpx;
				letter-spacing: 0rpx;
				color: #000000;				
				padding-left: 60rpx;
			}
		}
	}
	.section-2{
		width: 100%;
		background-color: #1432cd;
		.section-body{
			background-color: #fff;
			border-top-left-radius: 50rpx;
			border-top-right-radius: 50rpx;
			overflow: hidden;
			box-sizing: border-box;
			padding: 40rpx 60rpx;
			 .title{
				font-size: 26rpx;
				font-weight: bold;
				font-stretch: normal;
				line-height: 34rpx;
				letter-spacing: 0rpx;
				color: #000000;
				margin-bottom: 35rpx;
				.delegate{
					float: right;
					font-size: 26rpx;
					font-weight: normal;
					font-stretch: normal;
					line-height: 34rpx;
					letter-spacing: 0rpx;
					color: #1432cd;
				}
			 }
			 .duty-action{
				width: 630rpx;
				height: 163rpx;
				background-color: #1534ce;
				box-shadow: 0rpx 13rpx 35rpx 0rpx 
					rgba(60, 90, 214, 0.42);
				border-radius: 35rpx;
				box-sizing: border-box;
				padding-top: 25rpx;
				.sub-title{
					width: 100%;
					text-align: center;
					font-family: SourceHanSansCN-Medium;
					font-size: 26rpx;
					font-weight: normal;
					font-stretch: normal;
					letter-spacing: 0rpx;
					color: #ffffff;
				}
				.duty-time{
					width: 100%;
					text-align: center;
					margin-top: 10rpx;
					font-size: 58rpx;
					font-weight: bold;
					font-stretch: normal;
					letter-spacing: 0rpx;
					color: #ffffff;
				}
			 }
			 .duty-action__disabled{
				 background: linear-gradient(0deg, #f68461, #ffae78);
			 }
			 .location{
				 width: 100%;
				 text-align: center;
				 margin-top: 25rpx;
				font-size: 16rpx;
				font-weight: 300;
				font-stretch: normal;
				
				letter-spacing: 0rpx;
				color: #7f98ae;
				.iconfont{
					font-size: 16rpx;
				}
			 }
			 .warning{
				 width: 100%;
				 text-align: center;
				 margin-top: 13rpx;
				font-family: SourceHanSansCN-Light;
				font-size: 16rpx;
				font-weight: normal;
				font-stretch: normal;
				line-height: 21rpx;
				letter-spacing: 0rpx;
				color: #ff0000;
			 }
		}
	}
	.section-1{
		width: 100%;
		background-color: #1534ce;
		.section-body{
			width: 674rpx;
			height: 90rpx;
			line-height: 90rpx;
			margin-left: 40rpx;
			margin-right: 40rpx;
			background-color: #1534ce;
			background-size: cover;
			background-repeat: no-repeat;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			box-sizing: border-box;
			box-shadow: 0rpx 15rpx 10rpx 0rpx rgba(0,0,0,0.05) inset;
			font-size: 26rpx;
			color: #94c4fa;
			.icon-xiangmu{
				font-size: 26rpx;
				margin-right: 15rpx;
			}
		};
	}
	.section-0{
		width: 100%;
		background-color: #2e5efe;
		.top{
			width: 100%;
			background: #1534ce;
			background-size: cover;
			background-repeat: no-repeat;
			border-top-left-radius: 50rpx;
			border-top-right-radius: 50rpx;
			overflow: hidden;
			.user-info{
				width: 100%;
				box-sizing: border-box;
				padding-left: 55rpx;
				padding-top: 35rpx;
				padding-bottom: 35rpx;
				@include clear;
				.logo{
					width: 140rpx;
					height: 140rpx;
					background-color: #ffffff;
					border-radius: 14rpx;
					box-sizing: border-box;
					padding: 8rpx;
					float: left;
					image{
						width: 100%;
						height: 100%;
						border-radius: 10rpx;
					}
				}
				.info{
					float: left;
					padding-left: 35rpx;
					.name{
						.icon{
							float: left;
							margin-right: 35rpx;
							image{
								height: 50rpx;
								width: 35rpx;
							}
						}
						width: 100%;
						height: 50rpx;
						font-size: 35rpx;
						line-height: 50rpx;
						font-weight: normal;
						font-stretch: normal;
						letter-spacing: 0rpx;
						color: #ffffff;
						margin-top: 20rpx;
						margin-bottom: 20rpx;
					}
					.job{
						width: 100%;
						height: 50rpx;
						.icon{
							float: left;
							margin-right: 35rpx;
							width: 35rpx;
							image{
								height: 50rpx;
								width: 35rpx;
							}
						}
						font-size: 35rpx;
						line-height: 50rpx;
						font-weight: normal;
						font-stretch: normal;
						letter-spacing: 0rpx;
						color: #ffffff;
					}
				}
			}
		}
	}
	.section-4{
		width: 100%;
		border-radius: 50rpx;
		background-color: #fafbfd;
		padding-top: 50rpx;
		padding-bottom: 20rpx;
		box-shadow: 0rpx -10rpx 29rpx 8rpx rgba(#bcbcb5, 0.19);
		position: relative;
		top: 0;
	}
	.pop {
		width: 671rpx;
		padding-bottom: 40rpx;
		background-color: #fff;
		-webkit-border-radius: 35rpx;
		-moz-border-radius: 35rpx;
		border-radius: 35rpx;
		overflow: hidden;
		.actions{
			width: 100%;
			display: flex;
			justify-content: space-between;
			.cancel{
				background-color: #395cf5;
			}
		}
		/deep/ .mescroll-uni-fixed {
			position: inherit;
		}
		
		.title {
			width: 100%;
			height: 96rpx;
			line-height: 96rpx;
			background-color: #1534ce;
			font-size: 42rpx;
			font-weight: normal;
			font-stretch: normal;
			letter-spacing: 4rpx;
			color: #ffffff;
			text-align: center;
		}
		
		.form-item{
			
				width: 600rpx;
				height: 48rpx;
				line-height: 48rpx;
				margin: 0 auto;
				margin-bottom: 25rpx;
				display: flex;
				align-items: center;
			
				&:last-child {
					margin-bottom: 34rpx;
				}
			
				&.upload-wrap {
					align-items: unset;
					height: unset;
					line-height: unset;
				}
			
				@include clear();
			
				.label {
					float: left;
					width: 130rpx;
					height: 48rpx;
					text-align: left;
					line-height: 44rpx;
					font-size: 26rpx;
					color: #46464a;
				}
			
				/deep/ .u-upload__wrap {
					width: calc(100% - 206rpx) !important;
					background-color: transparent;
				}
			
				.icon-tupian {
					position: absolute;
					right: 25rpx;
					line-height: 44rpx;
					color: #1534ce;
					font-size: 28rpx;
				}
			
				/deep/ .u-radio-label--left {
					margin-right: 55rpx;
				}
			
				/deep/ .u-radio__text {
					font-size: 26rpx !important;
					color: #46464a !important;
				}
			
				.text-area {
					float: left;
					width: calc(100% - 134rpx - 3rpx);
					border-radius: 20rpx;
					border: solid 2rpx #1534ce;
			
					.input-body {
						box-sizing: border-box;
						width: 100%;
						height: 44rpx;
						padding: 0 !important;
						border: none;
						padding-left: 30rpx !important;
						padding-right: 30rpx !important;
						font-size: 26rpx;
						font-weight: normal;
						font-stretch: normal;
						letter-spacing: 0rpx;
						color: rgba(0, 0, 0, 0.7);
					}
			
					.text-body {
						box-sizing: border-box;
						width: 100%;
						height: 400rpx;
						border: none;
						padding: 10rpx 25rpx!important;
						font-size: 26rpx;
						font-weight: normal;
						font-stretch: normal;
						letter-spacing: 0rpx;
						color: rgba(0, 0, 0, 0.7);
						background: none;
					}
						
					.input-placeholder {
						font-size: 26rpx;
						font-weight: normal;
						font-stretch: normal;
						letter-spacing: 0rpx;
						color: rgba(0, 0, 0, 0.5);
					}
				}
			
		}
		.textarea-wrap{
			height: 400rpx;
			display: block;
		}
		
	}
</style>
